package me.numark.activities;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.numark.R;
import me.numark.fragments.AskLoginFragment;
import me.numark.fragments.BaseListFragment;
import me.numark.model.Feed;
import me.numark.model.FeedResponse;
import me.numark.model.FeedTag;
import me.numark.model.FeedTagResponse;
import me.numark.model.PublishCommentResponse;
import me.numark.model.Topic;
import me.numark.model.TopicListResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;
import me.numark.view.FeedViewHolder;
import me.numark.view.TopicAdapter;

/**
 * Created by Evan on 15/7/25.
 */
public class MarkDetailActivity extends BaseActivity implements View.OnClickListener,
        UltimateRecyclerView.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener{


    @Bind(R.id.input_layout_a)
    LinearLayout inputLayout;

    @Bind(R.id.ultimate_recycler_view)
    UltimateRecyclerView ultimateRecyclerView;
    @Bind(R.id.inputbar)
    FrameLayout inputbar;
    @Bind(R.id.input_edit_a)
    EditText inputEdit;
    @Bind(R.id.input_btn)
    Button inputButton;

    @Bind(R.id.layout_mark_detail)
    LinearLayout parentView;

    @Bind(R.id.right_image)
    ImageView rightImage;
    /*@Bind(R.id.text_num)
    TextView inputNum;*/
    protected boolean needLogin = false;
    private View headerView;
    ArrayList dataList;
    private OnCommentsFragmentInteractionListener mListener = null;
    public static final String EXTRA_ORIG_TYPE = "orig_type";
    private Feed mFeed;
    FeedViewHolder mFeedViewHolder;
    int mOrigType;
    BaseListFragment[] fragments;
    Dialog dialog;
    TopicAdapter mTopicAdapter;
    View loadMoreView = null;
    long lastResponseTime;
    boolean needHiddenavatarLayout = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_mark_detail;
        super.onCreate(savedInstanceState);
        try {
            mFeed = new Gson()
                    .fromJson(getIntent().getStringExtra(Constants.FEED_EXTRA), Feed.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            finish();
        }

        mOrigType = getIntent().getIntExtra(EXTRA_ORIG_TYPE, Constants.FEEDTYPE_NONE);
        if (mOrigType == Constants.FEEDTYPE_TAG_HOT){
            needHiddenavatarLayout = true;
        }else if(mOrigType == Constants.FEEDTYPE_USER_LIKES){
            if (getIntent().getBooleanExtra(Constants.NOTICE_IS_NEWS,false)){
                needHiddenavatarLayout = true;
            }else
                needHiddenavatarLayout = false;

        }
        uiInit();
        refresh();
    }

    protected void uiInit() {
        titleTextView.setText(R.string.detail_title);
        headerView = LayoutInflater.from(this).inflate(R.layout.feed_list_item, ultimateRecyclerView, false);
        mFeedViewHolder = new FeedViewHolder(headerView, this, Constants.FEEDTYPE_DETAIL, true, needHiddenavatarLayout);
        mFeedViewHolder.mOrigFeedType = mOrigType;
        mFeedViewHolder.bindData(mFeed, null, mFeed.position);


        inputLayout.setVisibility(View.VISIBLE);
        //actionArea.setVisibility(View.GONE);

        //inputButton.setOnClickListener(this);
        //inputEdit.setOnKeyListener(onKey);

        rightImage.setVisibility(View.VISIBLE);
        rightImage.setImageResource(R.drawable.action_bar_more);
        rightImage.setOnClickListener(this);
        parentView.setOnClickListener(this);
        dataList = new ArrayList();

        mTopicAdapter = new TopicAdapter(null, dataList, this,mFeed.id,Constants.TOPICTYPE_LIST);
        ultimateRecyclerView = (UltimateRecyclerView) findViewById(R.id.ultimate_recycler_view);
        ultimateRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        ultimateRecyclerView.setAdapter(mTopicAdapter);
        ultimateRecyclerView.setNormalHeader(headerView);
        ultimateRecyclerView.enableLoadmore();
        ultimateRecyclerView.setOnLoadMoreListener(this);
        ultimateRecyclerView.setDefaultOnRefreshListener(this);
        ultimateRecyclerView.mSwipeRefreshLayout.setColorSchemeResources(R.color.btn_green);
        loadMoreView = LayoutInflater.from(this)
                .inflate(R.layout.custom_bottom_progressbar, ultimateRecyclerView, false);
        ultimateRecyclerView.enableLoadmore();
        mTopicAdapter.setCustomLoadMoreView(loadMoreView);

        ultimateRecyclerView.disableLoadmore();

        ultimateRecyclerView.setRecylerViewBackgroundColor(Color.parseColor("#efefef"));
        ultimateRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                onClickComment(null);

            }
        });

        inputButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Global.isLoggedIn()) {
                    AskLoginFragment.show(MarkDetailActivity.this);
                }else {
                    publishLabel();
// 隐藏输入法
                    InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
// 显示或者隐藏输入法
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }

            }
        });

        /*inputEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if ((actionId==EditorInfo.IME_ACTION_DONE
                        ||(event!=null && event.getKeyCode()==KeyEvent.KEYCODE_ENTER))){
                    if (!Global.isLoggedIn()) {
                        AskLoginFragment.show(MarkDetailActivity.this);
                    }else {
                        publishLabel();
                    }
                }
                return false;
            }
        });*/

        /*inputEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = inputEdit.getText().toString().length();
                if (number > 80){
                    inputNum.setTextColor(Color.parseColor("#ff0000"));
                }else{
                    inputNum.setTextColor(Color.parseColor("#999999"));
                }
                inputNum.setText("" + number);
            }
        });*/
    }
    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * 更改标签状态
     * @param feedTag
     */
    public void updateTimeLineLabelStatus(FeedTag feedTag){
       mFeed.deleteFeedTag = null;
       mFeed.addFeedTag = null;
       mFeed.updateFeedTag=feedTag;
       notifyToRefresh();
    }

    /**
     * 删除标签
     * @param feedTag
     */
    public void onClickComment(FeedTag feedTag) {
        if (feedTag!=null){
            mFeed.addFeedTag = null;
            mFeed.updateFeedTag = null;
            mFeed.deleteFeedTag = feedTag;
            showDialog(feedTag.id);
        }
    }

    void showDialog(final long id) {
        View view = getLayoutInflater().inflate(R.layout.delete_topic, null);
        Button deleteBtn = (Button) view.findViewById(R.id.btn_delete);
        Button cancelBtn = (Button)view.findViewById(R.id.btn_cancel);

        deleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (id != 0) {
                    //TODO 发起删除标签请求
                    new RequestServerTask<FeedResponse>(FeedResponse.class) {
                        @Override
                        protected String requestServer() {
                            String url = String.format(NetworkConstants.LABEL_DELETE, Global.getCurrentUid());
                            Map<String, Object> map = new HashMap();
                            map.put("label_id", id);
                            return HttpUtil.post(url, map);
                        }

                        @Override
                        protected void onSuccess(FeedResponse result) {
                            if (needHiddenavatarLayout) {
                                if (mFeed.news.label_num>1)
                                    mFeed.news.label_num--;
                            }else {
                                if (mFeed.label_num>1)
                                    mFeed.label_num--;
                            }
                            //TODO 发送广播通知关注页刷新
                            notifyToRefresh();
                            for (int i = 0; i < dataList.size(); i++) {
                                FeedTag feedTag = (FeedTag) dataList.get(i);
                                if(id == feedTag.id) {
                                    mTopicAdapter.remove(dataList, i+1);
                                    break;
                                }
                            }
                            mFeedViewHolder.bindData(mFeed, null, mFeed.position);

                        }
                    }.start();
                }
            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();

        window.setWindowAnimations(R.style.menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();

        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.right_image:
                mFeedViewHolder.showMore();
                break;
        }
    }



    public void publishLabel() {
        final String text = inputEdit.getText().toString().trim();
        if (text.length() == 0) {
            Utils.showSnackbar(rootView,R.string.comment_empty_input);
            return;
        }
        if (text.length()>80){
            Utils.showSnackbar(rootView,R.string.text_num_is_too_more);
            return;
        }
        new RequestServerTask<FeedTagResponse>(FeedTagResponse.class,
                this,
                getString(R.string.progress_comment)) {
            @Override
            protected String requestServer() {
                String url = String.format(NetworkConstants.PUBLISH_LABEL, Global.getCurrentUid(), mFeed.news.id);
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("tid",mFeed.id);
                params.put("nid",mFeed.news.id);
                params.put("label", text);
                return HttpUtil.post(url, params);
            }

            @Override
            protected void onSuccess(FeedTagResponse result) {
                inputEdit.setText("");
                onClickComment(null);
                Utils.showSnackbar(rootView,R.string.commit_succ);
                mFeed.addFeedTag = result.data;
                mFeed.deleteFeedTag = null;
                mFeed.updateFeedTag = null;
                if (needHiddenavatarLayout) {
                    mFeed.news.label_num++;
                }else {
                    mFeed.label_num++;
                }
                mFeedViewHolder.bindData(mFeed, null, mFeed.position);
                //TODO news中label数量需要+1
                //TODO 返回的label标签需要通过position传递给外部的指定条目
                notifyToRefresh();
                refresh();
            }
        }.start();
    }

    private void notifyToRefresh(){
        Intent intent = new Intent();
        intent.setAction(Constants.NOTIFY);
        if (mFeed!=null) {
            Bundle bundle = new Bundle();
            bundle.putString(Constants.NOTIFY_ACTION, mFeed.toString());
            intent.putExtras(bundle);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        }
    }

    private View.OnKeyListener onKey = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode==KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP){
                publishLabel();
            }
            return false;
        }
    };

    public interface OnCommentsFragmentInteractionListener {
        public void onClickComment(Topic topic);
    }


    public void enableRefresh(boolean value) {
        ultimateRecyclerView.mSwipeRefreshLayout.setEnabled(value);
    }

    @Override
    public void loadMore(int itemsCount, final int maxLastVisiblePosition) {
        loadData(itemsCount);
    }

    @Override
    public void onRefresh() {
        loadData(0);
    }

    public void setHasMore(boolean hasMore) {
        if (hasMore) {
            ultimateRecyclerView.reenableLoadmore(loadMoreView);
        } else {
            ultimateRecyclerView.disableLoadmore();
        }
    }

    public void refresh() {
        onRefresh();
        ultimateRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                ultimateRecyclerView.setRefreshing(true);
            }
        });
    }



    public void endRefreshing() {
        ultimateRecyclerView.setRefreshing(false);
    }

    protected void bindData(BaseResponse response, boolean isNew) {
        if (response.ret) {

            addDataToList(response, isNew);
            mTopicAdapter.notifyDataSetChanged();
        }
        if (mTopicAdapter.getAdapterItemCount() == 0) {
        } else {
            ultimateRecyclerView.hideEmptyView();
        }
    }

    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, TopicListResponse.class);
    }

    protected void addDataToList(BaseResponse response, boolean isNew) {
        TopicListResponse resp = (TopicListResponse) response;
        if (isNew) {
            mTopicAdapter.clear();
        }
        mTopicAdapter.append(resp.data);
        setHasMore(resp.has_more);
    }

    protected String getFeedUrl() {
        /*//TODO 修改了这里 原来是获取评论列表 现在是获取标签列表
        return String.format(NetworkConstants.MARK_COMMENT_URL, Global.getCurrentUid(), mFeed.mid);*/
        if (mFeed.id==0) {
            return String.format(NetworkConstants.GET_LABELS, mFeed.news.id);
        }else {
            return String.format(NetworkConstants.GET_LABELS,mFeed.id);
        }
    }

    protected void loadData(final int start) {
        if (needLogin && Global.currentUser == null) {
            endRefreshing();
            return;
        }
        new RequestServerTask<TopicListResponse>(TopicListResponse.class) {
            @Override
            protected String requestServer() {
                int type;
                if (mFeed.id==0){
                    type = 0 ;
                }else {
                    type = 1;
                }
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("start", String.valueOf(start));
                params.put("limit", String.valueOf(Constants.PAGE_SIZE));
                params.put("type",String.valueOf(type));
                if (start > 0 && lastResponseTime > 0) {
                    params.put("time", String.valueOf(lastResponseTime));
                }
                return HttpUtil.post(getFeedUrl(), params, null, null);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(TopicListResponse result) {
                bindData(result, start == 0);
            }
        }
                .setSnackbarView(rootView)
                .start();
    }

   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            if (inputLayout.getVisibility() == View.VISIBLE){
                inputLayout.setVisibility(View.GONE);
                actionArea.setVisibility(View.VISIBLE);
                return false;
            }

            onBackPressed();
        }

        return false;

    }*/

    protected boolean checkLogin() {
        if (Global.isLoggedIn()) {
            return true;
        }
        AskLoginFragment.show(this);
        return false;
    }
}
